<?php
require_once '../db.php';
require '../vendor/autoload.php'; // 引入 Composer 自动加载器

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$secretKey = 'your_secret_key'; // 与普通用户和审核不同的密钥

if (!isset($_COOKIE['token'])) {
    header('Location: index.php');
    exit();
}

$jwt = $_COOKIE['token'];

try {
    $decoded = JWT::decode($jwt, new Key($secretKey, 'HS256'));
    $username = $decoded->data->username;
    $admin_role = $decoded->data->role;
    $user_id = $decoded->data->id;
} catch (Exception $e) {
    echo json_encode([
        'error' => '访问被拒绝: ' . $e->getMessage()
    ]);
    exit();
}

if ($admin_role !== 'su_admin') {
    http_response_code(403);
    echo json_encode(["message" => "Forbidden"]);
    exit();
}

header('Content-Type: application/json');

// 获取请求方法
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $result = $conn->query("SELECT * FROM announcements");
    $announcements = $result->fetch_all(MYSQLI_ASSOC);
    echo json_encode($announcements);
} elseif ($method === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    $title = $conn->real_escape_string($data['title']);
    $content = $conn->real_escape_string($data['content']);
    $conn->query("INSERT INTO announcements (title, content) VALUES ('$title', '$content')");
    echo json_encode(['success' => $conn->affected_rows > 0]);
} elseif ($method === 'DELETE') {
    $data = json_decode(file_get_contents('php://input'), true);
    $id = $conn->real_escape_string($data['id']);
    $conn->query("DELETE FROM announcements WHERE id = $id");
    echo json_encode(['success' => $conn->affected_rows > 0]);
}

$conn->close();

?>
